//go:build linux

package onet

import (
	"github.com/panjf2000/gnet/v2"
	"net"
)

type conn struct {
	c gnet.Conn
}

func (c conn) Next(n int) (buf []byte, err error) {
	return c.c.Next(n)
}

func (c conn) Peek(n int) (buf []byte, err error) {
	return c.c.Peek(n)
}

func (c conn) Discard(n int) (discarded int, err error) {
	return c.c.Discard(n)
}

func (c conn) InboundBuffered() (n int) {
	return c.c.InboundBuffered()
}

func (c conn) AsyncWrite(buf []byte) (err error) {
	return c.c.AsyncWrite(buf, nil)
}

func (c conn) OutboundBuffered() (n int) {
	return c.c.OutboundBuffered()
}

func (c conn) Close() (err error) {
	return c.c.Close()
}

func (c conn) Context() (ctx any) {
	return c.c.Context()
}

func (c conn) SetContext(ctx any) {
	c.c.SetContext(ctx)
}

func (c conn) LocalAddr() (addr net.Addr) {
	return c.c.LocalAddr()
}

func (c conn) RemoteAddr() (addr net.Addr) {
	return c.c.RemoteAddr()
}

type GnetEventHandler struct {
	*gnet.BuiltinEventEngine
	eventHandler EventHandler
}

func NewGnetEventHandler(eventHandler EventHandler) *GnetEventHandler {
	return &GnetEventHandler{eventHandler: eventHandler}
}

func (eh *GnetEventHandler) OnOpen(c gnet.Conn) (out []byte, action gnet.Action) {
	eh.eventHandler.OnOpen(&conn{c: c})
	return
}

func (eh *GnetEventHandler) OnClose(c gnet.Conn, err error) (action gnet.Action) {
	eh.eventHandler.OnClose(&conn{c: c}, err)
	return
}

func (eh *GnetEventHandler) OnTraffic(c gnet.Conn) (action gnet.Action) {
	eh.eventHandler.OnData(&conn{c: c})
	return
}

func Run(eventHandler EventHandler, protoAddr string, opts ...gnet.Option) (err error) {
	return gnet.Run(NewGnetEventHandler(eventHandler), protoAddr, opts...)
}
